import axios from 'axios'
import { getQueryVariable } from '@/utils/utils'
import { showToast } from 'vant'

let href = window.location.href
if (href.indexOf('?') !== -1) {
  href = href.split('?')[0]
}
let Request = GetRequest()
let currentPath = Request['currentPath']
let open_id = localStorage.getItem('open_id')

var baseURL = 'https://ya30api.hbwlife.com/wxmp'
const instance = axios.create({
  headers: {
    'Content-Type': 'application/json;charset=utf8',
  },
  baseURL: baseURL,
  timeout: 3000000,
  withCredentials: false,
})

function GetRequest() {
  var url = window.location.href //获取url中"?"符后的字串
  var theRequest = new Object()
  let index = url.indexOf('?')
  if (index != -1) {
    var str = url.substring(index)
    let strs = str.split('&')
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
    }
  }
  return theRequest
}

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    var user_id = localStorage.getItem('user_id')
    var access_token = localStorage.getItem('access_token')
    var open_id = localStorage.getItem('open_id')
    if (access_token) {
      config.headers['AUTH-TOKEN'] =
        user_id + '|' + access_token + '|' + open_id
    }
    return config
  },
  (error) => {}
)

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (response.data && response.data.code == 0) {
        return response
      } else if (response.data && response.data.code == -56055) {
        //showToast('登录已超时，即将重新登录')
        if (currentPath) {
          wx &&
            wx.miniProgram.redirectTo({
              url:
                '/pages/loginToken/index?currentPath=' +
                encodeURIComponent(currentPath),
            })
        }
        return response
      } else if (response.data && response.data.code == -57001) {
        //未注册,也就是没有手机号,因为在h5中tab页面onMounted中做判断了,应该走不到这了。
        //showToast('请先注册')
        if ((currentPath && !open_id) || open_id == '') {
          setTimeout(() => {
            wx &&
              wx.miniProgram.redirectTo({
                url:
                  '/pages/loginPhone/loginPhone?currentPath=' +
                  encodeURIComponent(currentPath),
              })
          }, 1500)
        } else {
        }
        return response
      }
    }
    return response
  },
  (error) => {
    return Promise.reject(error.response.data)
  }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function getData(url, data) {
  return new Promise((resolve, reject) => {
    instance
      .get(baseURL + url, {
        params: data,
      })
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} data [请求时携带的参数]
 * @param {Object} config 配置参数
 */
export function postData(url, data, config = {}) {
  return new Promise((resolve, reject) => {
    //console.log(baseURL + url);
    instance
      .post(baseURL + url, data, config)
      .then((res) => {
        // console.log(res.data);
        resolve(res.data)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}
